<template>
  <div
    class="container flex flex-col min-h-screen bg-primary"
    style="display: block"
  >
    <div class="header bg-primary shadow-lg sticky top-0 z-10 pr-40 pl-40">
      <div
        class="nav flex flex-col sm:flex-row items-center gap-4 text-white py-6"
      >
        <div class="flex items-center gap-3">
          <i class="fa-solid fa-sun text-2xl"></i>
          <p class="text-2xl">新中地天气</p>
        </div>
        <div class="flex gap-4 items-center">
          <h4 class="text-lg">{{ result2.city }}</h4>
          <span class="text-sm"
            >实时天气：{{ result2.weather }} {{ result2.temperature }}℃</span
          >
          <span class="text-sm"
            >{{ result2.winddirection }}风{{ result2.windpower }}级</span
          >
        </div>
        <div class="flex gap-3 flex-1 justify-end">
          <i
            class="fa-solid fa-circle-info text-xl hover:text-secondary cursor-pointer duration-1000"
            @click="showInfoClick()"
          ></i>
          <i
            class="fa-solid fa-plus text-xl hover:text-secondary duration-150 cursor-pointer"
            @click="savelocalStorage()"
            v-show="isshow"
          ></i>
        </div>
      </div>
    </div>
    <div class="content text-white">
      <div class="p-2 text-center bg-secondary">
        你正在预览{{ result.city }}的天气信息<span
          >，可以通过右上角的"+"号按钮保存起来</span
        >
      </div>
      <div class="flex flex-col text-center mt-6 gap-4">
        <h1>当日气温是：{{ result.temperature }}摄氏度</h1>
        <h1>当日天气是：{{ result.weather }}</h1>
        <h1>当日风向是：{{ result.winddirection }}风</h1>
        <h1>当日风力是：{{ result.windpower }}级</h1>
      </div>
      <hr class="border-white border-opacity-10 mt-6" />
      <div class="pr-40 pl-40">
        <div class="bg-secondary px-12 pt-10 mt-2 rounded">
          <div class="list flex gap-6">
            <div
              class="flex flex-col flex-1 text-center gap-4"
              v-for="(item, index) in resultall"
              :key="index"
            >
              <span>{{ item.day }}</span>
              <span>{{ item.date }}</span>
              <span>{{ item.dayweather }}</span>
              <span>风力 {{ item.daypower }}级</span>
            </div>
          </div>
          <div class="echart">
            <div ref="chartRef" style="width: 100%; height: 220px"></div>
          </div>
        </div>
      </div>
    </div>

    <div
      class="fixed z-20 w-full bg-opacity-30 bg-black h-screen top-0 left-0 flex justify-center px-8"
      :class="{ hidden: !showInfo }"
    >
      <div class="p-4 bg-white self-start mt-32 max-w-screen-md">
        <h2>关于:</h2>
        <p class="text-xs mb-4">这个应用可以用来追踪你选择城市的当前天气</p>
        <h2>如何使用:</h2>
        <p class="text-xs mb-4">
          1.点击搜索框输入你希望追踪的城市<br />
          2.在搜索结果中选中一个城市，你将获取当地最新的天气<br />
          3.点击右侧的＋号可以将追踪城市的天气情况保存在首页
        </p>
        <h2>移除城市:</h2>
        <p class="text-xs">
          如果你不想在首页关注某个城市,可以通过底部的按钮删<br />除它
        </p>
        <button
          class="text-white mt-8 bg-primary py-2 px-6 text-xs"
          @click="toggleInfo()"
        >
          关闭
        </button>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted, computed } from 'vue'
import * as echarts from 'echarts'
import axios from 'axios'
//接收pinia传过来的数据
import { storeToRefs } from 'pinia'
import { useCounterStore } from '@/stores/counter'
const { count } = storeToRefs(useCounterStore())
// console.log(count.value, '222')

const chartRef = ref(null) // 创建一个ref来引用图表容器
const showInfo = ref(false)
const result = ref('')
const resultall = ref([])
const result1 = ref('')
const result2 = ref('')
const res = ref('')
const option = ref('')
const day = []
const night = []
const nowday = ref('')
const currentDate = ref('')
const tomorrowday = ref('')
const week = ['周日', '周一', '周二', '周三', '周四', '周五', '周六']
const savecity = ref([])
const isshow = ref(false)

//保存数据到本地
function savelocalStorage() {
  isshow.value = false
  if (localStorage.getItem('savecity')) {
    savecity.value = JSON.parse(localStorage.getItem('savecity'))
  }
  let city = {
    adcode: result.value.adcode,
    city: result.value.city,
    temp: result.value.temperature,
  }
  // console.log(savecity.value)
  savecity.value.push(city)
  localStorage.setItem('savecity', JSON.stringify(savecity.value))
  // alert('已保存')
}

// 模态框的显示隐藏切换
function toggleInfo() {
  showInfo.value = !showInfo.value
}
// 模态框的点击事件
function showInfoClick() {
  toggleInfo()
}
//发送axios请求获取天气数据
async function getWeatherData() {
  //获取武汉的adcode
  const response = await axios.get(
    'https://restapi.amap.com/v3/ip?key=513d613dba4b77bf8089ab3e2822b6c2'
  )
  result1.value = response.data
  // console.log(result1.value,'444')
  //获取武汉实时天气数据
  const response2 = await axios.get(
    `https://restapi.amap.com/v3/weather/weatherInfo?city=${result1.value.adcode}&key=513d613dba4b77bf8089ab3e2822b6c2&extensions=base`
  )
  result2.value = response2.data.lives[0]

  //获取被查询城市的实时天气数据
  res.value = count.value
  const response3 = await axios.get(
    `https://restapi.amap.com/v3/weather/weatherInfo?city=${res.value}&key=513d613dba4b77bf8089ab3e2822b6c2&extensions=base`
  )
  // console.log(response3, '333')
  result.value = response3.data.lives[0]
  //  console.log(result.value, '111')

  //获取被查询城市未来几天的天气数据
  const response4 = await axios.get(
    `https://restapi.amap.com/v3/weather/weatherInfo?city=${res.value}&key=513d613dba4b77bf8089ab3e2822b6c2&extensions=all`
  )

  //将数组中数字转换为星期
  resultall.value = response4.data.forecasts[0].casts
  resultall.value.map((item) => {
    nowday.value = week[new Date().getDay()]
    // console.log(nowday.value, 'nowday')
    currentDate.value = new Date()
    tomorrowday.value =
      week[new Date(currentDate.value.getTime() + 24 * 60 * 60 * 1000).getDay()]
    // console.log(tomorrowday.value, 'tomorrowday')
    item.day = week[new Date(item.date).getDay()]
    if (item.day === nowday.value) {
      item.day = '今天'
    } else if (item.day === tomorrowday.value) {
      item.day = '明天'
    }
  })
  // console.log(resultall.value, '555')
  //筛选出白天和夜晚的气温数据
  day.value = resultall.value.map((item) => +item.daytemp)
  // console.log(day.value)
  night.value = resultall.value.map((item) => +item.nighttemp)
  // console.log(night.value)
  renderChart()
}
//渲染图表
function renderChart() {
  let chart = echarts.init(chartRef.value) // 初始化echarts图表
  option.value = {
    grid: {
      top: '30%',
      left: 0,
      right: 0,
      bottom: 0,
    },
    xAxis: {
      type: 'category',
      show: false,
    },
    yAxis: {
      type: 'value',
      show: false,
    },
    series: [
      {
        type: 'line',
        data: day.value,
        label: {
          show: true,
          position: 'top',
          color: 'white',
          //格式化标签显示内容
          formatter: function (params) {
            return '白' + params.value + '°C'
          },
        },
      },
      {
        type: 'line',
        data: night.value,
        label: {
          show: true,
          position: 'bottom',
          color: 'white',
          formatter: function (params) {
            return '晚' + params.value + '°C'
          },
        },
      },
    ],
  }
  chart.setOption(option.value) // 设置图表配置
}
const checkCity = computed(() => {
  return savecity.value.every((item) => item.adcode !== count.value)
})
function isshows () {
  isshow.value = checkCity.value
}
onMounted(() => {
  getWeatherData() // 获取天气数据
  
  savecity.value = JSON.parse(localStorage.getItem('savecity')) || []
  // console.log(savecity.value, 'savecity666')
  
  // console.log(checkCity.value, 'checkCity')
  isshows()
})
</script>

<style scoped></style>
